A loop is set of instructions which allows you to apply one or more custom code operations repeatedly throughout a predetermine number of cycles (aka loops)
What is a programming loop?
https://contest-server.cs.uchicago.edu
Neccessary Components of a Programming Loop
Iterator or counter
marks how many loops have occurred
Code to be run repeatedly
part of the code doing the actual work!
Exit condition
determines when to stop looping
Let’s say you wanted to find the mean and standard deviation of each row in this matrix
The counter variable can be named anything you like
R will iterate through whatever you declare after the in operator and assign it to the counter variable
dragons <-c("Vhagar","Caraxes","Syrax","Meleys")for (dragon in dragons){print(paste(dragon, "the fearsome", sep=" "))}
[1] "Vhagar the fearsome"
[1] "Caraxes the fearsome"
[1] "Syrax the fearsome"
[1] "Meleys the fearsome"
Looping to Z-score Normalize
Now let’s use these same calculations to create a z-scored version of the orignal matrix
# First create empty output objectzscored <-matrix(nrow=nrow(mymatrix), ncol=ncol(mymatrix))for (i in1:nrow(mymatrix)){#Then loop through rows using i to calculate the row statistics mean <-mean(mymatrix[i,]) sd <-sd(mymatrix[i,])#Then use these values to normalize each entry in the matrixfor (j in1:ncol(mymatrix)){ zscored[i,j] <- (mymatrix[i,j] - mean)/sd }}zscored
Looping to Z-score Normalize
Now let’s use these same calculations to create a z-scored version of the orignal matrix
Code
zscored <-matrix(nrow=3, ncol=5)for (i in1:nrow(mymatrix)){#First calculate the row statistics mean <-mean(mymatrix[i,]) sd <-sd(mymatrix[i,])#Then use these values to normalize each entry in the matrixfor (j in1:ncol(mymatrix)){ zscored[i,j] <- (mymatrix[i,j] - mean)/sd }}zscored
library(tictoc)myBIGmatrix <-matrix(rnorm(1500, mean=10, sd=3),nrow=300, ncol=500 )BIGzscored <-matrix(nrow=nrow(myBIGmatrix), ncol=ncol(myBIGmatrix))tic()for (i in1:nrow(myBIGmatrix)){#First calculate the row statistics mean <-mean(myBIGmatrix[i,]) sd <-sd(myBIGmatrix[i,])#Then use these values to normalize each entry in the matrixfor (j in1:ncol(myBIGmatrix)){ BIGzscored[i,j] <- (myBIGmatrix[i,j] - mean)/sd }}toc()
0.044 sec elapsed
Some advice on when to use loops
Vectorized functions save compute time with large datasets, but the difference is minimal if you are not dealing with a lot of data points.